﻿using Coments.Service;
using Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyWebTest
{
    public partial class Test : System.Web.UI.Page
    {
        List<SynFileInfo> list;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //List<string> pids = new List<string>();
                //pids.Add("c2bbb032-02ed-4484-821c-5f4a8e53c349");

                //var data = CounterService.GetGroupCounterList("evaluate_good", pids);

                string key = "test";
                RedisCacheManager.AddListCache(key, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                var data = RedisCacheManager.GetListCache(key);
                if (data != null)
                {
                    labDisplay.Text = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }

                labIsConnected.Text = (DownloadTest.IsConnected() ? "网络正常" : "网络不正常") + "  下载时间：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                BindData();
            }
        }

        string GetNames()
        {
            return "test";
        }

        #region 添加下载任务并显示到列表中

        void AddBatchDownload()
        {
            if (list == null)
                list = new List<SynFileInfo>();
            //添加列表(建立多个任务)
            List<ArrayList> arrayListList = new List<ArrayList>();
            arrayListList.Add(new ArrayList(){
                "0",//文件id
                "PPTV客户端.exe",//文件名称
                "21.2 MB",//文件大小
                "0 KB/S",//下载速度
                "0%",//下载进度
                "http://download.pplive.com/pptvsetup_3.2.1.0076.exe",//远程服务器下载地址
                "D:\\MyDownloads\\" +"PPTV客户端.exe",//本地保存地址
                true//是否异步
            });
            arrayListList.Add(new ArrayList(){
                "1",
                "PPS客户端.exe",
                "14.3 MB",
                "0 KB/S",
                "0%",
                "http://download.ppstream.com/ppstreamsetup.exe",
                "D:\\MyDownloads\\" +"PPS客户端.exe",
                true
            });
            arrayListList.Add(new ArrayList(){
                "2",
                "美图看看客户端.exe",
                "4.1 MB",
                "0 KB/S",
                "0%",
                "http://kankan.dl.meitu.com/V2/1029/KanKan_kk360Setup.exe",
               "D:\\MyDownloads\\" + "美图看看客户端.exe",
                true
            });

            foreach (ArrayList arrayList in arrayListList)
            {
                arrayList[2] = 0;
                //取出列表中的行信息保存列表集合(m_SynFileInfoList)中
                list.Add(new SynFileInfo(arrayList.ToArray()));
            }
        }

        #endregion

        void BindData()
        {
            if (list == null)
            {
                AddBatchDownload();
            }
            gv_DownLoad.DataSource = list;
            gv_DownLoad.DataBind();
        }

        #region 使用WebClient下载文件

        /// <summary>
        /// HTTP下载远程文件并保存本地的函数
        /// </summary>
        void StartDownLoad(object o)
        {
            SynFileInfo m_SynFileInfo = (SynFileInfo)o;
            m_SynFileInfo.LastTime = DateTime.Now;
            //再次new 避免WebClient不能I/O并发 
            WebClient client = new WebClient();
            if (m_SynFileInfo.Async)
            {
                //异步下载
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                client.DownloadFileAsync(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath, m_SynFileInfo);
            }
            else client.DownloadFile(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath);
        }

        /// <summary>
        /// 下载进度条
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;
            m_SynFileInfo.SynProgress = e.ProgressPercentage + "%";
            double secondCount = (DateTime.Now - m_SynFileInfo.LastTime).TotalSeconds;
            m_SynFileInfo.SynSpeed = FileOperate.GetAutoSizeString(Convert.ToDouble(e.BytesReceived / secondCount), 2) + "/s";
            list.ForEach(x =>
            {
                if (x.DocID == m_SynFileInfo.DocID)
                {
                    x.SynProgress = m_SynFileInfo.SynProgress;
                    x.SynSpeed = m_SynFileInfo.SynSpeed;
                }
            });

            BindData();
        }

        /// <summary>
        /// 下载完成调用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //到此则一个文件下载完毕
            SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState;
        }

        #endregion

        protected void btn_Download_Click(object sender, EventArgs e)
        {
            var btn = (Button)sender;
            var docID = btn.CommandArgument;
            if (!string.IsNullOrEmpty(docID))
            {
                if (list == null)
                {
                    AddBatchDownload();
                }
                var info = list.FirstOrDefault(x => x.DocID == docID);
                StartDownLoad(info);
            }
        }

        protected void btn_DownloadFile_Click(object sender, EventArgs e)
        {
            string url = txt_Url.Text + "";
            string ext = url.Substring(url.LastIndexOf('.'));
            string filePath = saveFileUpload.FileName;
            var arrayList = new ArrayList()
            {
                "1",//文件id
                "文件名",//文件名称
                "0 MB",//文件大小
                "0 KB/S",//下载速度
                "0%",//下载进度
                url,//远程服务器下载地址
                filePath,//本地保存地址
                true//是否异步
            };

            arrayList[2] = 0;
            //取出列表中的行信息保存列表集合(m_SynFileInfoList)中
            var info = new SynFileInfo(arrayList.ToArray());

            StartDownLoad(info);
        }
    }
}